package com.km.wskj.itmonitor.pager.mine;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.km.wskj.itmonitor.LApplication;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.UpdateService;
import com.km.wskj.itmonitor.pager.MainActivity;
import com.km.wskj.itmonitor.pager.base.LFragment;
import com.km.wskj.itmonitor.pager.im.IMHelper;
import com.km.wskj.itmonitor.pager.login.LoginActivity;
import com.km.wskj.itmonitor.pager.login.RegSendCodeActivity;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.control.VersionControl;
import com.zxl.zxlapplibrary.util.InstallApkUtil;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import mehdi.sakout.fancybuttons.FancyButton;
import okhttp3.Call;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/2/9.
 */
//设置界面
public class SettingFragment extends LFragment {

    //ui
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right)
    ImageView toolBarRight;
    @BindView(R.id.mine_zrcListView)
    ZrcListView mZrcListView;
    @BindView(R.id.set_head)
    CircleImageView setHead;
    @BindView(R.id.tv_set_user)
    TextView tvSetUser;
    @BindView(R.id.tv_set_reg)
    TextView tvSetReg;
    @BindView(R.id.tv_set_login)
    TextView tvSetLogin;
    @BindView(R.id.btn_logout)
    FancyButton btnLogout;
    @BindView(R.id.ll_login_layout)
    LinearLayout loginLayout;

    private List<String> mItem = new ArrayList<>();
    private int[] icons = new int[]{R.mipmap.mine_mine, R.mipmap.mine_about
            , R.mipmap.update, R.mipmap.mine_url};

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        //沉浸shi
        StatusBarCompat.compat(getActivity(), Color.parseColor("#27a0f0"));
        ButterKnife.bind(this, view);
        initView();
        initData();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
    }

    @Override
    public void onPause() {
        super.onPause();
        initView();
    }

    private void initView() {

        if (pdc.mCurrentUser != null) {
            tvSetUser.setVisibility(View.VISIBLE);
            tvSetUser.setText(pdc.mCurrentUser.nickname);
            btnLogout.setVisibility(View.VISIBLE);
            loginLayout.setVisibility(View.GONE);
            Glide.with(getActivity())
                    .load(pdc.mCurrentUser.host + pdc.mCurrentUser.headImg)
                    .into(setHead);
        }
    }

    private void initData() {
//        toolBarRight.setVisibility(View.VISIBLE);
        toolBarTitle.setText("我的");

        //设置栏目数量
        mItem.add("个人信息");
        mItem.add("关于我们");
        mItem.add("检查更新");
        mItem.add("设置服务器监控地址");

        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#eeeeee"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        mZrcListView.setAdapter(new MyAdapter());

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                switch (position) {
                    //修改个人信息
                    case 0:
                        //判断当前用户是否登陆
                        if (pdc.mCurrentUser == null) {
                            normalToasty("请先登录");
                            startActivity(new Intent(getContext(), LoginActivity.class));
                            return;
                        }
                        Intent t = new Intent(getActivity(), SetUserInfoActivity.class);
                        startActivity(t);

                        break;
                    case 1:

                        break;
                    //检查更新
                    case 2:
                        checkUpdate();
                        break;
                    //设置服务器监控地址
                    case 3:
                        //判断当前用户是否登陆
                        if (pdc.mCurrentUser == null) {
                            normalToasty("请先登录");
                            startActivity(new Intent(getContext(), LoginActivity.class));
                            return;
                        }
                        startActivity(new Intent(getActivity(), SetHostUrlActivity.class));
                        break;

                }
            }
        });

    }

    @OnClick(R.id.tool_bar_right)
    public void onClick() {
        Intent t = new Intent(getActivity(), SetActivity.class);
        startActivity(t);
    }

    @OnClick({R.id.tv_set_reg, R.id.tv_set_login, R.id.btn_logout})
    public void onClick(View view) {
        switch (view.getId()) {
            //注册
            case R.id.tv_set_reg:
                startActivity(new Intent(getActivity(), RegSendCodeActivity.class));
                break;
            //登陆
            case R.id.tv_set_login:
                startActivity(new Intent(getActivity(), LoginActivity.class));
                break;

            //退出登陆
            case R.id.btn_logout:
                pdc.logout();//退出登陆
                tvSetUser.setVisibility(View.GONE);
                loginLayout.setVisibility(View.VISIBLE);
                btnLogout.setVisibility(View.GONE);
                setHead.setImageResource(R.mipmap.no_login);
                logout();//环信退出的方法
                break;
        }
    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mItem == null) {
                return 0;
            }
            return mItem.size();
        }

        @Override
        public Object getItem(int position) {
            String s = mItem.get(position);
            return s;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            BaseAdapterHelper helper = BaseAdapterHelper.get(getActivity()
                    , convertView, parent, R.layout.setting_item_listview);
            helper.setText(R.id.tv_item_name, mItem.get(position));
            helper.setImageResource(R.id.iv_item_icon, icons[position]);
            return helper.getView();
        }
    }

    private void checkUpdate() {
        final ProgressDialog dlg = ProgressDialog.show(getActivity(), "检查更新", "请稍后...", true);
        final VersionControl vc = LApplication.app.vc;

        if (vc.isFirUpdateAvailable()) {
            vc.requestFirVersion(vc.new FirVersionCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    dlg.dismiss();
                    LogUtils.e("request xtkj update server fail", e);
                }

                @Override
                public void onResponse(Object response, int id) {
                    dlg.dismiss();
                    if (vc.checkVersion() > 0) {
                        installUpdate();
                    } else {
                        normalToasty("当前已是最新版");
                    }
                }
            });
        }
    }

    private void installUpdate() {
        final VersionControl vc = LApplication.app.vc;
        InstallApkUtil i = new InstallApkUtil(getActivity(), getActivity().getPackageName(),
                "app.apk", vc.apkUrl, vc.must == 1);//
        if (vc.must == 1) {
            i.installFromUrl("版本更新", "检测到新版本:" + vc.versionName + "\n" + vc.updateInfo
                    + "\n需要立即更新");
        } else {
            i.installFromUrl("版本更新", "检测到新版本:" + vc.versionName + "\n" + vc.updateInfo
                    + "\n是否立即更新");
        }
    }

    //环信退出的方法
    private void logout() {
        final ProgressDialog pd = new ProgressDialog(getActivity());
        String st = getResources().getString(R.string.Are_logged_out);
        pd.setMessage(st);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        IMHelper.getInstance().logout(false, new EMCallBack() {

            @Override
            public void onSuccess() {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        // show login screen
                      /*  ((MainActivity) getActivity()).finish();
                        startActivity(new Intent(getActivity(), LoginActivity.class));*/

                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getActivity(), "unbind devicetokens failed", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

}
